package com.example.administrator.xiaoxiang.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/1/4.
 */

public  class BaseTypeAdapter extends RecyclerView.Adapter<BaseViewHolder> {

    protected LayoutInflater mInflater;
    protected Context mContext;
    private Map<Integer,Integer> layoutMap=new HashMap<>();
    private OnItemClickListener mOnItemClickListener = null;
    private List<LayoutWrapper> items=new ArrayList<>();

    public interface OnItemClickListener {
        void OnClick(View view, int position);
    }

    public BaseTypeAdapter(Context context, int[] layoutIds) {
        this.mInflater = LayoutInflater.from(context);
        this.mContext = context;
        for (int i=0;i<layoutIds.length;i++){
            layoutMap.put(i,layoutIds[i]);
        }

    }


    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(getLayoutId(viewType), parent, false);
        return new BaseViewHolder(view, (BaseAdapter.OnItemClickListener) mOnItemClickListener);
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        LayoutWrapper wrapper = items.get(position);
        wrapper.getHolder().bind(mContext,holder,wrapper.getData(),position);
    }

    @Override
    public int getItemViewType(int position) {

        return getViewType(position);
    }

    @Override
    public int getItemCount() {
        if (items == null && items.size() <= 0)

            return 0;
        return items.size();
    }


    public void setData(List<LayoutWrapper> list){
        this.items=list;
        notifyDataSetChanged();
    }
   //根据ViewType获取LayoutID
    public int getLayoutId(int viewType){
        return layoutMap.get(viewType);
    }
    //LayoutId转ViewType
    public  int getViewType(int position) {
        LayoutWrapper wrapper = items.get(position);
        Iterator iter = layoutMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry= (Map.Entry) iter.next();
            Integer key= (Integer) entry.getKey();
            Integer val= (Integer) entry.getValue();
            if (val==wrapper.getLayoutId()){
                return key;
            }
        }
    return 0;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }
}
